package com.coocaa.aries.jmeter.util;

import com.coocaa.aries.jmeter.constant.PhantomJsConfigConstants;
import com.coocaa.aries.jmeter.yml.PhantomJsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @author : bijiahao
 * @date : 2019/5/24.
 * @description: phantomjs 命令组装类
 */
@Slf4j
public class PhantomJsCmdBuilder {

    private PhantomJsProperties phantomJsProperties;

    public PhantomJsCmdBuilder(PhantomJsProperties phantomJsProperties) {
        this.phantomJsProperties = phantomJsProperties;
    }


    public boolean execHtml2Pdf(String fileInPath, String fileOutPath) throws Exception {
        Runtime runtime = Runtime.getRuntime();
        String cmd = getHtml2PdfCmd(fileInPath, fileOutPath);
        Process process = runtime.exec(cmd);
        process.waitFor();
        Integer res = process.exitValue();
        return res == 0;
    }

    /**
     * @param fileInPath
     * @param fileOutPath
     * @return <p>
     * <p>
     * phantomjs /Users/bijiahao/bjh-project/mine-git-project2018/coocaa-faster/coocaa-jmeter/target/classes//cmd/html2Pdf.js /Users/bijiahao/log/report/20190401/278658/index.html /Users/bijiahao/log/report/20190401/278658/index.pdf
     * </p>
     */
    private String getHtml2PdfCmd(String fileInPath, String fileOutPath) {
        String scriptPath = getScriptPath();
        log.info("\n====Html2Pdf scriptPath: " + scriptPath);
        StringBuilder cmd = new StringBuilder();
        cmd.append("phantomjs ")
                .append(scriptPath)
                .append(" ")
                .append(fileInPath)
                .append(" ")
                .append(fileOutPath);
        return cmd.toString();

    }

    /**
     * 获取脚本路径
     *
     * @return
     */
    private String getScriptPath() {
        if (StringUtils.isNotBlank(phantomJsProperties.getScriptPath())) {
            return phantomJsProperties.getScriptPath();
        }
        return PathUtil.getClassPath() + PhantomJsConfigConstants.SCRIPT_FILE_RELATIVE_FILE;
    }
}
